package com.nintendo.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
public class JwtUtils {
    // 使用固定的密钥，确保所有地方使用相同的密钥
    private static final String SECRET_KEY_STRING = "nintendoApplicationSecretKeyWithAtLeast64CharactersForHS512Algorithm";
    private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(SECRET_KEY_STRING.getBytes(StandardCharsets.UTF_8));

    // 从配置文件读取密钥（可选）
    @Value("${jwt.secretKey:}")
    private static String secretKeyFromConfig;

    private  SecretKey getSigningKey() {
        // 如果配置文件中有密钥且不为空，使用配置的密钥
        if (secretKeyFromConfig != null && !secretKeyFromConfig.isEmpty()) {
            return Keys.hmacShaKeyFor(secretKeyFromConfig.getBytes(StandardCharsets.UTF_8));
        }
        // 否则使用固定的密钥
        return SECRET_KEY;
    }

    // 生成Token
    public  String generateToken(String username, Long userId) {
        return Jwts.builder()
                .setId(userId.toString())
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 24小时
                .signWith(getSigningKey(), SignatureAlgorithm.HS512)
                .compact();
    }
    public  String generateToken(String username, String userId) {
        return Jwts.builder()
                .setId(userId.toString())
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 86400000)) // 24小时
                .signWith(getSigningKey(), SignatureAlgorithm.HS512)
                .compact();
    }
    // 验证Token并解析用户名
    public  Claims extractClaims(String token) {
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(getSigningKey())
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
            return claims;
        } catch (Exception e) {
            // 记录详细的错误信息
            System.err.println("JWT validation failed: " + e.getMessage());
            throw e;
        }
    }
    // 验证Token并解析用户名（保持原有方法以确保向后兼容）
    public  String extractUsername(String token) {
        try {
            Claims claims = Jwts.parserBuilder()
                    .setSigningKey(getSigningKey())
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
            return claims.getSubject();
        } catch (Exception e) {
            // 记录详细的错误信息
            System.err.println("JWT validation failed: " + e.getMessage());
            throw e;
        }
    }


}
